package com.huadao.cart_ccs.netty;

import android.util.Log;

import com.huadao.cart_ccs.data.bo.BaseBO;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class NettyClientHandler extends SimpleChannelInboundHandler<BaseBO> {

    private NettyListener listener;
    private String TAG="NettyClientHandler";

    public NettyClientHandler(NettyListener listener){
        this.listener = listener;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        NettyClient.getInstance().setConnectStatus(true);
        listener.onServrStatusConnectChanged(NettyListener.STATUS_CONNECT_SUCCESS);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        NettyClient.getInstance().setConnectStatus(false);
        listener.onServrStatusConnectChanged(NettyListener.STATUS_CONNECT_CLOSED);
        NettyClient.getInstance().reconnect();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, BaseBO baseBO) throws Exception {
        Log.i("NettyClientHandler","channelRead0");
//        listener.onMessageResponse(new TestDecoder().decode(byteBuf));
        listener.onMessageResponse(baseBO);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE){
                Log.i(TAG,"读超时");
            }else if (event.state() == IdleState.WRITER_IDLE){
                Log.i(TAG,"写超时");
            }
        }else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
